﻿using System;
using System.Runtime.Serialization;
using System.IO;
using System.IO.Compression;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;

namespace Desktop.Library
{
    [Serializable()]
    public class SessionManager : ISerializable
    {
        #region Constructors

        static SessionManager()
        {
            Instance = new SessionManager();
        }

        private SessionManager()
        {
            UserPreferences = new UserPreferences();
            StoryList = new List<Story>();
        }

        private SessionManager(SerializationInfo info, StreamingContext context)
        {
            UserPreferences = info.GetValue("UserPreferences", typeof(UserPreferences)) as UserPreferences;
            StoryList = info.GetValue("StoryList", typeof(List<Story>)) as List<Story>;
        }

        #endregion

        #region Properties

        public static SessionManager Instance { get; private set; }

        public UserPreferences UserPreferences { get; private set; }
        public List<Story> StoryList { get; private set; }

        #endregion

        #region Methods

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("UserPreferences", UserPreferences);
            info.AddValue("StoryList", StoryList);
        }

        public static void Save(string filename)
        {
            FileStream stream = File.Create(filename);
            GZipStream zipStream = new GZipStream(stream, CompressionMode.Compress);
            try
            {
                BinaryFormatter bin = new BinaryFormatter();
                bin.Serialize(zipStream, Instance);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                zipStream.Close();
                stream.Close();
            }
        }

        public static void Load(string filename)
        {
            FileStream stream = File.OpenRead(filename);
            GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress);
            BinaryFormatter bin = new BinaryFormatter();

            try
            {
                Instance = bin.Deserialize(zipStream) as SessionManager;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                zipStream.Close();
                stream.Close();
            }
        }

        #endregion
    }
}